
package com.wyzz.hr.base;

import com.wyzz.hr.dao.ISysconfigDAO;
import com.wyzz.hr.dao.impl.SysconfigDAOImpl;
import com.wyzz.hr.pojo.Sysconfig;
import com.wyzz.hr.spring.SpringBeanFactory;
import com.wyzz.hr.util.impl.PropertiesFileConfigManager;

import java.io.*;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.axis.utils.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ObjectUtils;


public class FileOperate extends BaseAction {

	public FileOperate() {
	}

	public static String buildFile(String originalFile,
			String newFilePathConfig, String newFileName,
			String extendNameConfig, String lengthConfig) {
		try {
			File original = new File(originalFile);
			return buildFile(original, newFilePathConfig, extendNameConfig,
					lengthConfig, new String[] { newFileName });
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "error";
	}

	public static String buildFile(File fileObject, String filePathConfig,
			String extendNameConfig, String lengthConfig, String fileNames[]) {
		String returnVal;
		if (ObjectUtils.isEmpty(fileNames) || fileNames.length == 0)
			return "property";
		int pointPlace;
		String extendNameLimit;
		String fileLengthLimit;
		String originalExtendName;
		try {
			pointPlace = fileNames[0].lastIndexOf(".");
			if (pointPlace == -1 || pointPlace >= fileNames[0].length())
				return "error";
		} catch (Exception e) {
			e.printStackTrace();
			return "property";
		}
		if (extendNameConfig != null) {
			extendNameLimit = getProperty(extendNameConfig);
			originalExtendName = fileNames[0].substring(pointPlace)
					.toLowerCase();
			if (extendNameLimit != null
					&& extendNameLimit.indexOf(originalExtendName) == -1)
				return "fileExtendNameError";
		}
		if (lengthConfig != null) {
			fileLengthLimit = getProperty(lengthConfig);
			if (fileLengthLimit != null
					&& fileObject.length() > (long) (Integer
							.parseInt(fileLengthLimit.trim()) * 1024))
				return "fileTooLength";
		}
		returnVal = buildFile(fileObject, filePathConfig, fileNames[0]);
		if ("success".equals(returnVal) && fileNames.length > 1
				&& !StringUtils.isEmpty(fileNames[1])
				&& !fileNames[1].equals(fileNames[0]))
			return deleteFile(filePathConfig, fileNames[1]);
		return returnVal;
	}

	public static String buildFile(String originalFilePath,
			String newFilePathConfig, String fileName) {
		try {
			File originalFile = new File(originalFilePath);
			return buildFile(originalFile, newFilePathConfig, fileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "error";
	}

	public static String buildFile(File file, String filePathConfig,
			String fileName) {
		try {
			String filePath = null;
			if (filePathConfig != null)
				filePath = (new StringBuilder()).append(getFileHomePath())
						.append(getProperty(filePathConfig)).toString();
			else
				filePath = getFileHomePath();
			File newFile = new File(filePath);
			if (!newFile.exists())
				newFile.mkdirs();
			String fileAbsolutPath = (new StringBuilder()).append(filePath)
					.append(fileName).toString();
			FileCopyUtils.copy(file, new File(fileAbsolutPath));
		} catch (IOException e) {
			e.printStackTrace();
			return "error";
		}
		return "success";
	}

	public static FileInputStream getFileInputStream(String filePathConfig,
			String fileName) {
		File file;
		file = getFile(filePathConfig, fileName);
		if (file == null)
			return null;
		try {
			return new FileInputStream(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static File getFile(String filePathConfig, String fileName) {
		File file;
		String filePath = null;
		if (filePathConfig != null)
			filePath = (new StringBuilder()).append(getFileHomePath()).append(
					getProperty(filePathConfig)).toString();
		else
			filePath = getFileHomePath();
		file = new File((new StringBuilder()).append(filePath).append(fileName)
				.toString());
		if (!file.exists())
			return null;
		try {
			return file;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String deleteFile(String filePathConfig, String fileName) {
		try {
			String deleteFilePath = null;
			if (filePathConfig != null)
				deleteFilePath = (new StringBuilder())
						.append(getFileHomePath()).append(
								getProperty(filePathConfig)).append(fileName)
						.toString();
			else
				deleteFilePath = (new StringBuilder())
						.append(getFileHomePath()).append(fileName).toString();
			File file = new File(deleteFilePath);
			return deleteFile(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "property";
	}

	public static String deleteFile(File file) {
		if (file.exists())
			file.delete();
		return "success";
	}

	public static String getFileHomePath() {
		HttpServletRequest request = ServletActionContext.getRequest();
		if (request == null)
			request = WebContextFactory.get().getHttpServletRequest();
		String path = request.getSession().getServletContext().getRealPath("");
		// String filePath = (new File(path)).getParentFile().getAbsolutePath();
		ISysconfigDAO sysDAO = (SysconfigDAOImpl) SpringBeanFactory
				.getBean("sysDAO");
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Sysconfig.class);
		detachedCriteria.add(Restrictions.eq(Sysconfig.PROP_SYSCONFIG_KEY,
				"sys.file.path"));
		List list = sysDAO.findByCriteria(detachedCriteria);
		String readPath = "";
		if (list != null && list.size() > 0)
			readPath = ((Sysconfig) list.get(0)).getSysconfigValue();
		File file;
		if (readPath.length() < 1) {
			path = (new StringBuilder()).append(path).append("/file/")
					.toString();
			file = new File(path);
			if (!file.exists())
				file.mkdirs();
			return path;
		}
		path = (new StringBuilder()).append(path).append("/").append(readPath)
				.toString();
		file = new File(path);
		if (!file.exists())
			file.mkdirs();
		return path;
	}

	public static String buildFileByInputStream(InputStream inputStream,
			String fileName, String filePath) {
		byte buffer[];
		OutputStream bos;
		buffer = new byte[8192];
		int length = -1;
		File tempFile = new File(filePath);
		if (!tempFile.exists())
			tempFile.mkdirs();
		File file = new File(filePath, fileName);
		bos = null;
		try {
			bos = new BufferedOutputStream(new FileOutputStream(file));
		} catch (FileNotFoundException e) {
			return "FileNotFoundException";
		}
		do {
			try {
				length = inputStream.read(buffer);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			if (length == -1)
				break;
			try {
				bos.write(buffer, 0, length);
			} catch (IOException e) {
				return "IOException";
			}
		} while (true);
		try {
			bos.close();
			inputStream.close();
		} catch (IOException e) {
			return "IOException";
		}
		return "success";
	}

	public static String sqlCmdCompose(String sqlCommand) {
		PropertiesFileConfigManager fileConfigManager = PropertiesFileConfigManager
				.getInstance();
		String result = (new StringBuilder()).append("/").append(sqlCommand)
				.append(" -h").toString();
		String url = fileConfigManager.getProperty("jdbc.url");
		String urlArr[] = url.split("://");
		result = (new StringBuilder()).append(result).append(
				urlArr[1].split("/")[0].split(":")[0]).append(" -u").toString();
		String dataBase = fileConfigManager.getDatabaseSchemaName();
		String userName = fileConfigManager.getProperty("jdbc.username");
		String password = fileConfigManager.getProperty("jdbc.password");
		result = (new StringBuilder()).append(result).append(userName).append(
				password == null || password.equals("") ? ""
						: (new StringBuilder()).append(" -p").append(password)
								.toString()).append(" ").append(dataBase)
				.append(" --default-character-set=utf8 ").toString();
		if ("mysqldump".equals(sqlCommand))
			result = (new StringBuilder()).append(result).append("> ")
					.toString();
		else if ("mysql".equals(sqlCommand))
			result = (new StringBuilder()).append(result).append("< ")
					.toString();
		return result;
	}

	public static String buildFileName() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString();
	}

	private static String getProperty(String key) {
		PropertiesFileConfigManager configManager = PropertiesFileConfigManager
				.getInstance();
		return configManager.getProperty(key);
	}

	private static final long serialVersionUID = 1L;
	public static final String SUCCESS = "success";
	public static final String ERROR = "error";
	public static final String PROPERTY_ERROR = "property";
	public static final String LENGTH_ERROR = "fileTooLength";
	public static final String EXTEND_ERROR = "fileExtendNameError";
	public static final String IO_EXCEPTION = "IOException";
	public static final String FILE_NOT_FOUND_EXCEPTION = "FileNotFoundException";
}
